package com.zhongshengnetwork.rightbe.lang.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DeviceUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.FlowLayout;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangTypeModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.view.ZFlowLayout;
import com.zhongshengnetwork.rightbe.my.activity.FeedBackActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.rong.imlib.RongIMClient;

public class PublicTypeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private TopBarView topbar;
    private FlowLayout flowLayout;
    private String[] mLabels = {"名人名言","名人故事","读懂暗语","诗词改编","口才交际", "时尚热点", "新颖观点", "生活感悟", "创新思维", "面试问答","励志感人","词语解说","教育启蒙","幽默诙谐","经典台词"};
    private List<String> langNameList;
    private List<String> contentList;
    private HashMap<String, String> langNameMap;
    private int type = 0;
    private String typeName = "默认";

    private EditText search_edit;
    private Button search_button;
    private String dataContent = "";
    private ImageView no_data_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_type);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setVisibility(View.VISIBLE);
        topbar.getRightTextView().setText("说明");
        topbar.getRightTextView().setTextSize(14);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PublicTypeActivity.this, SelectPublishTypeActivity.class);
                startActivity(intent);
            }
        });

        RelativeLayout public_type = (RelativeLayout) findViewById(R.id.public_type);
        public_type.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        no_data_img = (ImageView) findViewById(R.id.no_data_img);
        no_data_img.setVisibility(View.INVISIBLE);

        search_edit = (EditText) findViewById(R.id.search_edit);
        search_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String search = search_edit.getText().toString().trim();
                    onClickSearch(textView);
                    return true;
                }
                return false;
            }
        });
        search_button = (Button) findViewById(R.id.search_button);
        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSearch(v);
            }
        });
        search_edit.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        search_edit.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        RelativeLayout search_top = (RelativeLayout) findViewById(R.id.search_top);
        search_top.setBackgroundColor(AppThemeUtils.getInstance().getSearchBgColor());
        RelativeLayout search_shape_layout = (RelativeLayout) findViewById(R.id.search_shape_layout);
        search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());

        initType();
        getDataAndUpdateUI("");
    }


    private void initType(){
        flowLayout = (FlowLayout) findViewById(R.id.mflowLayout);
        flowLayout.setColorful(false);
        langNameList = new ArrayList<String>();
        contentList = new ArrayList<String>();
        langNameMap = new HashMap<String, String>();
//        String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LangTypeName,"");
//        if (CommonUtils.isEmpty(data)){
//            for (int i = 0; i < mLabels.length; i++){
//                langNameList.add(mLabels[i]);
//                langNameMap.put(mLabels[i],(i+1)+"");
//            }
//        }else {
//            List<LangTypeModel>l = GsonTools.getLangTypeModel(data);
//            if (l != null && l.size() > 0){
//                Log.e("TAG","网络请求的数据\n");
//                for (int i = 0; i < l.size(); i++){
//                    LangTypeModel m = l.get(i);
//                    langNameList.add(m.getName());
//                    contentList.add(CommonUtils.formatString(m.getContent()));
//                    langNameMap.put(m.getName(),m.getId()+"");
//                }
//            }
//        }
//
//        String[] strArrayTrue = (String[]) langNameList.toArray(new String[0]);
//        flowLayout.setData(strArrayTrue);
        flowLayout.setOnTagClickListener(new FlowLayout.OnTagClickListener() {
            @Override
            public void TagClick(String text) {
                hintKeyBoard();
                String title = text;
                final int tag = langNameList.indexOf(title);
                String id = langNameMap.get(title);
                if (!CommonUtils.isEmpty(id)){
                    type = Integer.valueOf(id);
                    typeName = title;

                    CustomDialog dialog = null;
                    if (contentList == null || contentList.size() == 0){
                        final CustomDialog.Builder builder = new CustomDialog.Builder(PublicTypeActivity.this);
                        builder.setTitle("温馨提示");
                        builder.setMessage("你选择的类型是："+title);
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent intent = new Intent();
                                intent.putExtra("type",type);
                                intent.putExtra("typename",typeName);
                                setResult(RESULT_OK,intent);
                                finish();
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        dialog = builder.create();
                        dialog.show();
                    }else {
                        String content = contentList.get(tag);
                        final CustomDialog.Builder builder = new CustomDialog.Builder(PublicTypeActivity.this);
                        builder.setTitle(typeName);
                        builder.setMessage(content);
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                Intent intent = new Intent();
                                intent.putExtra("type",type);
                                intent.putExtra("typename",typeName);
                                setResult(RESULT_OK,intent);
                                finish();
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        dialog = builder.create();
                        dialog.show();
                    }

                }

            }
        });
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        dataContent = text;
        getDataAndUpdateUI(text);
    }

    private void getDataAndUpdateUI(String text){
        if (!CommonUtils.isEmpty(text) && !CommonUtils.isEmpty(text.trim())){
            KyLoadingBuilder dialog = new KyLoadingBuilder(PublicTypeActivity.this);
            dialog.setIcon(R.drawable.loading04);
            dialog.setText("加载中...");
            dialog.setOutsideTouchable(false);//点击空白区域是否关闭
            dialog.setBackTouchable(true);//按返回键是否关闭
            dialog.show();
            final HashMap<String, String> map = new HashMap<String, String>();
            if(CommonUtils.isLogin() == true){
                map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
            }
            String mobileid = DeviceUtils.getDeviceID();
            if (mobileid == null || mobileid.length() == 0){
                mobileid = "";
            }
            map.put("isFirst",false+"");
            map.put("type","100");
            map.put("mobileid",mobileid);
            map.put("uimode",CommonUtils.getUIMode()+"");
            map.put("text", CommonUtils.formatString(text));
            String url = "miniapp/langappid/getsearchtype.do";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                    if (commonModel.getFlag().equals("1")){
                                        langNameList.clear();
                                        contentList.clear();
                                        langNameMap.clear();
                                        List<LangTypeModel>l = GsonTools.getLangTypeModelBySearch(data);
                                        if (l != null && l.size() > 0){
                                            Log.e("TAG","网络请求的数据\n");
                                            for (int i = 0; i < l.size(); i++){
                                                LangTypeModel m = l.get(i);
                                                langNameList.add(m.getName());
                                                contentList.add(CommonUtils.formatString(m.getContent()));
                                                langNameMap.put(m.getName(),m.getId()+"");
                                            }
                                        }
                                        flowLayout.cleanTag();
                                        if (langNameList.size() > 0){
                                            no_data_img.setVisibility(View.INVISIBLE);
                                            flowLayout.setColorful(false);
                                            String[] strArrayTrue = (String[]) langNameList.toArray(new String[0]);
                                            flowLayout.setData(strArrayTrue);
                                        }else {
                                            no_data_img.setVisibility(View.VISIBLE);
                                        }
                                    }else {
                                        CustomApplication.showTip(commonModel, PublicTypeActivity.this);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onError(String msg) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dialog.dismiss();
                                    ToastUtil.show(PublicTypeActivity.this, "加载失败");
                                }
                            });
                        }
                    });
                }
            }).start();
        }else {
            no_data_img.setVisibility(View.INVISIBLE);
            langNameList.clear();
            contentList.clear();
            langNameMap.clear();
            String data = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.LangTypeName,"");
            if (CommonUtils.isEmpty(data)){
                for (int i = 0; i < mLabels.length; i++){
                    langNameList.add(mLabels[i]);
                    langNameMap.put(mLabels[i],(i+1)+"");
                }
            }else {
                List<LangTypeModel>l = GsonTools.getLangTypeModel(data);
                if (l != null && l.size() > 0){
                    Log.e("TAG","网络请求的数据\n");
                    for (int i = 0; i < l.size(); i++){
                        LangTypeModel m = l.get(i);
                        langNameList.add(m.getName());
                        contentList.add(CommonUtils.formatString(m.getContent()));
                        langNameMap.put(m.getName(),m.getId()+"");
                    }
                }
            }
            flowLayout.cleanTag();
            flowLayout.setColorful(false);
            String[] strArrayTrue = (String[]) langNameList.toArray(new String[0]);
            flowLayout.setData(strArrayTrue);
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        hintKeyBoard();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

}
